package structures.stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(6);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println();
            System.out.println("s(show) 显示全部数据");
            System.out.println("e(exit) 退出程序");
            System.out.println("a(add) 添加数据");
            System.out.println("g(get) 获取数据");
            key = scanner.next().charAt(0);
            switch (key) {
                case 's':
                    arrayStack.list();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                case 'a':
                    int data = scanner.nextInt();
                    arrayStack.push(data);
                    break;
                case 'g':
                    System.out.println(arrayStack.pop());
                    break;
            }
            System.out.println("------------------------");
        }
    }
}

class ArrayStack {
    private int maxSize;
    private int index = -1;
    private int[] array;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        array = new int[maxSize];
    }

    public boolean isEmpty() {
        return index < 0;
    }

    public boolean isFull() {
        return index >= (maxSize - 1);
    }

    public boolean push(int data) {
        if (!isFull()) {
            array[++index] = data;
            return true;
        }
        System.out.println("添加数据失败,已满");
        return false;
    }

    public int pop() {
        if (!isEmpty()) {
            return array[index--];
        }
        throw new RuntimeException("栈为空");
    }

    public void list() {
        while (!isEmpty()) {
            System.out.print(pop() + "\t");
        }
        System.out.println();
    }
}
